package server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import message.RpcRequestMessage;
import message.RpcResponseMessage;
import server.service.HelloService;
import server.service.factories.ServicesFactory;

import java.lang.reflect.Method;

@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage message) {
    RpcResponseMessage response = new RpcResponseMessage();
    response.setSequenceId(message.getSequenceId());
    try {
      // 获取真正的实现对象
      HelloService service = (HelloService)
              ServicesFactory.getService(Class.forName(message.getInterfaceName()));

      // 获取要调用的方法
      Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());

      // 调用方法
      Object invoke = method.invoke(service, message.getParameterValue());
      // 调用成功
      response.setReturnValue(invoke);
    } catch (Exception e) {
      e.printStackTrace();
      // 调用异常
      response.setExceptionValue(new Exception("rpc remote call error： "+e.getCause().getMessage()));
    }
    // 返回结果
    ctx.writeAndFlush(response);
  }

  public static void main(String[] args) throws Exception {
    RpcRequestMessage message = new RpcRequestMessage(
            1,
            "server.service.HelloService",
            "sayHello",
            String.class,
            new Class[]{String.class},
            new Object[]{"zhangsan"}
    );
    HelloService service = (HelloService)
            ServicesFactory.getService(Class.forName(message.getInterfaceName()));
    Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
    Object retValue = method.invoke(service, message.getParameterValue());
    System.out.println(retValue);
  }
}

